package com.atguigu.gulionline.service.base.handler;

import com.atguigu.gulionline.service.base.result.R;
import com.atguigu.gulionline.service.base.result.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(value = ArithmeticException.class)
    public R exception(ArithmeticException e){
//        e.printStackTrace();
        log.error(ExceptionUtils.getStackTrace(e));
        return R.error().code(28111).message("除数为0");
    }
    @ResponseBody
    @ExceptionHandler(value = BadSqlGrammarException.class)
    public R exception(BadSqlGrammarException e){
//        e.printStackTrace();
        log.error(ExceptionUtils.getStackTrace(e));
        return R.setResult(ResultCodeEnum.BAD_SQL_GRAMMAR);
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseBody
    public R error(HttpMessageNotReadableException e){
//        e.printStackTrace();
        log.error(ExceptionUtils.getStackTrace(e));
        return R.setResult(ResultCodeEnum.JSON_PARSE_ERROR);
    }

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public R exception(Exception e){
//        try{}catch(ArithmeticException e){}catch(Exception e){}
//        System.out.println("e = " + e);
//        e.printStackTrace();
        log.error(ExceptionUtils.getStackTrace(e));
        return R.error();
    }


}
